// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class RankItem extends cc.Component {

    @property(cc.Label)
    nick: cc.Label = null;

    @property(cc.Label)
    score: cc.Label = null;

    @property(cc.Sprite)
    head: cc.Sprite = null;

    @property(cc.Sprite)
    rankIcon: cc.Sprite = null;

    @property(cc.Label)
    rankLabel: cc.Label = null;

    @property({type:[cc.SpriteFrame]})
    noIcons:cc.SpriteFrame[] = [];

    onLoad () {
        // this.rankIcon.node.active = false
        // this.rankLabel.node.active = false
    }

    start () {

    }

    setData(obj) {
        if (obj.nickname || obj.nickName)
            this.nick.string = obj.nickName ? obj.nickName : obj.nickname
        if (obj.KVDataList && obj.KVDataList[0] && obj.KVDataList[0].value)
            this.score.string = obj.KVDataList[0].value + ' 步'

        if (obj.rank) {
            this.rankIcon.node.active = obj.rank <=  3
            this.rankLabel.node.active = obj.rank >  3
            if (obj.rank <= 3) {
                this.rankIcon.spriteFrame = this.noIcons[obj.rank - 1]
            }else{
                this.rankLabel.string = obj.rank + ''
            }
        }
            
        let self = this
        if( cc.sys.platform == cc.sys.WECHAT_GAME && obj.avatarUrl){
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        self.head.spriteFrame = new cc.SpriteFrame(texture);
                    } catch (e) {
                        self.head.node.active = false;
                    }
                }
                image.src = obj.avatarUrl;
            }
            catch (e) {
                this.head.node.active = false;
            }
        }
    }

    // update (dt) {}
}
